package net.siufung.market.base.dept.provider;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.siufung.core.model.enums.DeletedEnum;
import net.siufung.core.utils.CopyUtil;
import net.siufung.core.utils.StringPool;
import net.siufung.market.base.dept.mapper.IDeptMapper;
import net.siufung.market.base.dept.mapper.entity.Dept;
import net.siufung.market.base.user.api.IUserDeptApi;
import net.siufung.market.base.user.api.dto.UserDeptDto;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 陈建峰
 * @date 2022/11/17 2:44 下午
 * @since V1.0.0
 */
@Slf4j
@AllArgsConstructor
public class UserDeptProvider implements IUserDeptApi {

    private final IDeptMapper deptMapper;

    @Override
    public List<String> getChildDeptIdList(String parentDeptId) {
        List<Dept> deptList = Lists.newArrayList();
        if(StringPool.ZERO.equals(parentDeptId)){
            deptList = deptMapper.selectList(
                    new LambdaQueryWrapper<Dept>()
                            .eq(Dept::getDeleted, DeletedEnum.NOT.getValue())
                            .orderByAsc(Dept::getCreatedAt));
        } else {
            deptMapper.getChildDeptList(deptList, parentDeptId,
                    deptMapper.selectList(Wrappers.query()));
        }
        return deptList.stream().map(Dept::getId)
                .distinct().collect(Collectors.toList());
    }

    @Override
    public List<UserDeptDto> getDeptList(String[] deptIds) {
        List<UserDeptDto> deptApiDtoList = Lists.newArrayList();
        if(ArrayUtil.isNotEmpty(deptIds)){
            UserDeptDto deptApiDto;
            List<Dept> deptList = deptMapper.selectBatchIds(Arrays.asList(deptIds));
            for (Dept dept: deptList) {
                deptApiDto = new UserDeptDto();
                CopyUtil.copyProperties(dept, deptApiDto);
                deptApiDto.setDeptId(dept.getId());
                deptApiDtoList.add(deptApiDto);
            }
        }
        return deptApiDtoList;
    }
}
